package org.parademo.service;

import org.parademo.dao.AddressDao;
import org.parademo.dao.UserDao;
import org.parademo.model.AddressEntity;
import org.parademo.model.UserEntity;
import org.parademo.web.controller.util.ViewFormatterUtil;
import org.parademo.web.model.UserProfileView;

import java.util.List;

public class UserServiceImpl implements UserService {

    private final UserDao userDao;
    private final AddressDao addressDao;

    public UserServiceImpl(UserDao userDao, AddressDao addressDao) {
        this.userDao = userDao;
        this.addressDao = addressDao;
    }

    public UserEntity getUserById(long userId) {
        return userDao.retrieve(userId);
    }

    @Override
    public UserEntity getUserByUserName(String userName) {
        return userDao.retrieve(userName);
    }

    @Override
    public List<UserEntity> getUsers() {
        return userDao.getUsers();
    }

    @Override
    public void update(UserProfileView user) {
        
        UserEntity existingUser = userDao.retrieve(
                user.getUserId()
        );

        // todo: set data from user to existingUser

        existingUser.setFirstName(user.getFirstName());
        existingUser.setLastName(user.getLastName());
        existingUser.setBirthDate(ViewFormatterUtil.formatStringToDate(user.getBirthDate()));
        existingUser.setJoinDate(ViewFormatterUtil.formatStringToDate(user.getJoinDate()));

        // todo: get AddressEntity by user.addressId
        AddressEntity existingUserAddress = addressDao.getTopicById(
                user.getAddressId()
        );

        existingUserAddress.setId(user.getAddressId());
        existingUserAddress.setStreetName(user.getAddressStreetName());
        existingUserAddress.setHouseNumber(user.getAddressHouseNumber());
        existingUserAddress.setCity(user.getAddressCity());
        existingUserAddress.setZipCode(user.getAddressZipCode());

        // todo: set data from user to AddressEntity
        existingUser.setAddress(existingUserAddress);

        // todo: save user (will also save the address)
        userDao.update(existingUser);
    }

    @Override
    public void delete(UserEntity user) {
        userDao.delete(user);
    }
}
